package com.kingcore.director.search.concurrent;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;

import javax.swing.JOptionPane;

import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;

import wzw.util.I18nUtil;
import wzw.util.StringUtils;

import com.kingcore.director.base.ui.DirectorPanel;
import com.kingcore.director.main.MainFrame;
import com.kingcore.director.search.ui.LocalFileIndexBuilder;
import com.kingcore.director.search.ui.LocalSearchMainPanel;

/**
 * 
 * <p>生产者消费者模式->数据集消费者 </p>
 * @author Zeven on 2009-3-18
 * @version	1.0
 * @see		Object#equals(java.lang.Object)
 * @since	JDK5
 */
public class DataListConsumer implements Runnable {

	private final static Logger log = Logger.getLogger(DataListConsumer.class);
	private MainFrame mainFrame = null;
    private static BlockingQueue<List<Map<String,String>>> dataListqueue = null;
    private static LocalFileIndexBuilder ib = null;
    
	public DataListConsumer(
			BlockingQueue<List<Map<String, String>>> p_dataListqueue, MainFrame mainFrame) {
		dataListqueue = p_dataListqueue;
		this.mainFrame = mainFrame;
		ib = LocalFileIndexBuilder.getInstance(LocalFileIndexBuilder.ANALYZER, LocalFileIndexBuilder.LocalFileSystem_INDEX, true);
		
	}

	public void run() {
		long startTime = System.currentTimeMillis();
		List<Map<String, String>> dataList = null;
		List<Document> documentList = null;
		while (true) {
			try {
				dataList = dataListqueue.take(); 
				log.info("take from dataListqueue ...queue size is:"+dataListqueue.size()); 
				documentList = convertToDocumentList(dataList);
				ib.writeToIndex(documentList);
				if (dataList.size()<FileConsumerDataListProducer.Batch_Size_Write_To_Document) {
					double allTime = ((float)(System.currentTimeMillis()-startTime))/(60000.00);
					DecimalFormat df = new DecimalFormat("0.000");//格式化小数，不足的补0
					String allTimeStr = df.format(allTime);//返回的是String类型的
					String statusBar_creatingIndexFilesSuccess = I18nUtil.getBundleString( DirectorPanel.class, "statusBar_createdIndexFilesSuccess.Text");
					String info = StringUtils.replace(statusBar_creatingIndexFilesSuccess, "${allCostTime}", allTimeStr);
					log.info(info); 
					LocalSearchMainPanel.isBuildingIndexFile = false;  //创建索引完成
					MainFrame.getInstance().getLocalSearchMainPanel().setStatus(MainFrame.StatusBar_Index_One, info);
					JOptionPane.showMessageDialog(MainFrame.getInstance(), info);
					
					try {
						ib.close();
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
					}
					return; //stop
				}
				
			} catch (InterruptedException e) { 
				e.printStackTrace();
			} 
		}
	}
	
	/** 字段分隔符 
		 被索引的列: 内容 标签(多个用空格隔开) */
	 public static List<Document> convertToDocumentList(List<Map<String, String>> dataList) {
		 Map<String,String> map=null;
		 List<Document> ret = new ArrayList<Document>();
		 for (int i = 0; i < dataList.size(); i++) {
			map = (Map<String,String>) dataList.get(i); 
			StringBuffer idx = new StringBuffer();
			idx.append(map.get("path")).append(File.separator).append(map.get("name"));
			
			StringBuffer notToBeIndexed = new StringBuffer();
			notToBeIndexed.append( map.get("path") ).append(LocalFileIndexBuilder.DELIMETER)
				.append(map.get("size")).append(LocalFileIndexBuilder.DELIMETER)
				.append(map.get("lastModifiedTime"));
			
			StringBuffer toBeIndexed  = new StringBuffer();
			toBeIndexed.append( map.get("name")).append(LocalFileIndexBuilder.DELIMETER);
	//		.append(objOwnerName).append(LocalFileIndexBuilder.DELIMETER)
	//		.append(obj_name);  
			Field field0 = new Field( LocalFileIndexBuilder.IndexFieldName, idx.toString(),Field.Store.YES,Field.Index.UN_TOKENIZED);
			Field field1 = new Field( LocalFileIndexBuilder.Field_For_Index, toBeIndexed.toString(), Field.Store.YES, Field.Index.TOKENIZED);
			Field field2 = new Field( LocalFileIndexBuilder.Field_Not_Index, notToBeIndexed.toString(), Field.Store.YES, Field.Index.NO);
			    
	//		System.out.println(toBeIndexed.toString());
			
			Document doc = new Document();
			doc.add(field1);
			doc.add(field2);
			doc.add(field0);
			
			ret.add(doc);
		 }		 
		 return ret;
	}

}
